<template>
  <div class="habit-view">
    <div class="header">
      <div class="title">习惯</div>
      <div class="action">
        <div class="btn" @click="handleShowHabitModal">
          <i class="ri-add-large-fill"></i>
        </div>
      </div>
    </div>

    <!-- 习惯列表 -->
    <div v-show="store.habitList.length" class="habit-list">
      <div
        class="habit-item"
        :class="{
          active: store.currentHabit === habit
        }"
        @click="handleHabitItemClick(habit)"
        @contextmenu="handleShowRightMenu($event, habit)"
        v-for="habit in store.habitList"
        :key="habit.id"
      >
        <div class="habit-icon">
          <img
            :src="habit.icon ? habit.icon : '/src/assets/icon/yuexiao/1.webp'"
            alt=""
            class="icon"
          />
        </div>
        <div class="habit-info">
          <div class="habit-name">{{ habit.name }}</div>
          <div class="habit-stats">
            <span class="total-check"
              ><i
                class="ri-flashlight-fill"
                :class="{
                  active: habit.checkInRecords.length
                }"
              ></i>
              {{ habit.checkInRecords.length }} 天</span
            >
            <span class="streak-check"
              ><i
                class="ri-fire-fill"
                :class="{
                  active: getHabitStreakCount(habit)
                }"
              ></i>
              {{ getHabitStreakCount(habit) }} 天</span
            >
          </div>
        </div>
        <div class="habit-action"></div>
      </div>
    </div>
    <div v-show="store.habitList.length === 0" class="habit-empty empty">
      <img src="/src/assets/icon/app/空空如也.png" alt="" />
      <div class="title">当前还没有习惯奥</div>
      <p class="text">坚持让我们闪闪发光</p>
    </div>
    <Modal
      title="删除习惯"
      content="确认删除这个习惯吗？以前辛苦积累的数据都会被删掉。"
      v-model:visible="modalVisible"
      @comfirm="handleComfirm"
      @cancel="handleCancel"
    ></Modal>
    <Modal
      title="添加习惯"
      @cancel="handleCancelAddHabit"
      @comfirm="handleAddHabit"
      v-model:visible="habitModalVisible"
      class="habit-modal"
      width="500"
    >
      <template #default>
        <div class="add-habit">
          <div class="form">
            <div class="row icon">
              <span>图标</span>
              <div style="width: 350px" class="input">
                <IconSelect
                  v-model:icon="habitData.icon"
                  v-model:visible="showIconSelect"
                ></IconSelect>
              </div>
            </div>
            <div class="row title">
              <span>名称</span>
              <input v-model="habitData.name" type="text" placeholder="请输入习惯名称" />
            </div>
            <div class="row frequency">
              <span>频率</span>
              <div style="width: 350px" class="input">
                <Select
                  v-model:value="habitData.frequency.type"
                  size="small"
                  :default-value="'daily'"
                  :options="frequencyOptions"
                  style="width: 100%"
                >
                </Select>
              </div>
            </div>
            <div class="row start-date">
              <span>开始日期</span>
              <div style="width: 350px" class="input">
                <DatePicker v-model:value="startDate" :default-value="dayjs()"></DatePicker>
              </div>
            </div>
            <div class="row hold-time">
              <span>坚持天数</span>
              <div style="width: 350px" class="input">
                <Select
                  v-model:value="habitData.holdTime"
                  size="small"
                  :default-value="'forever'"
                  :options="holdTimeOptions"
                  style="width: 100%"
                >
                </Select>
              </div>
            </div>
          </div>
        </div>
      </template>
    </Modal>
    <Modal
      title="编辑习惯"
      @cancel="handleEditModalCancel"
      @comfirm="handleEditHabit"
      v-model:visible="editModalVisible"
      class="habit-modal"
      width="500"
    >
      <template #default>
        <div class="add-habit">
          <div class="form">
            <div class="row icon">
              <span>图标</span>
              <div style="width: 350px" class="input">
                <IconSelect
                  v-model:icon="editHabitData.icon"
                  v-model:visible="showIconSelect"
                ></IconSelect>
              </div>
            </div>
            <div class="row title">
              <span>名称</span>
              <input v-model="editHabitData.name" type="text" placeholder="请输入习惯名称" />
            </div>
            <div class="row frequency">
              <span>频率</span>
              <div style="width: 350px" class="input">
                <Select
                  v-model:value="editHabitData.frequency.type"
                  size="small"
                  :default-value="'daily'"
                  :options="frequencyOptions"
                  style="width: 100%"
                >
                </Select>
              </div>
            </div>
            <div class="row start-date">
              <span>开始日期</span>
              <div style="width: 350px" class="input">
                <DatePicker
                  v-model:value="editHabitData.startData"
                  :default-value="dayjs()"
                ></DatePicker>
              </div>
            </div>
            <div class="row hold-time">
              <span>坚持天数</span>
              <div style="width: 350px" class="input">
                <Select
                  v-model:value="editHabitData.holdTime"
                  size="small"
                  :default-value="'forever'"
                  :options="holdTimeOptions"
                  style="width: 100%"
                >
                </Select>
              </div>
            </div>
          </div>
        </div>
      </template>
    </Modal>
    <HabitRightMenu @action="handleRightMenuAction" ref="habitRightMenuRef"></HabitRightMenu>
  </div>
</template>

<script setup lang="ts">
import habitStore from '@renderer/store/habit'
import HabitRightMenu from '@renderer/components/rightMenu/HabitRightMenu.vue'
import dayjs from 'dayjs'
import { ref, reactive, toRaw } from 'vue'
import { DatePicker, Select } from 'ant-design-vue'
import IconSelect from '@renderer/components/IconSelect.vue'
import Modal from '@renderer/components/Modal.vue'
import { getIcons } from '@renderer/utils'

const store = habitStore()

const habitRightMenuRef = ref<InstanceType<typeof HabitRightMenu>>()

const modalVisible = ref(false)

const habitModalVisible = ref(false)

const editModalVisible = ref(false)

const showIconSelect = ref(false)

const startDate = ref(dayjs())

const iconMap = getIcons()

const frequencyOptions = [
  {
    label: '每天',
    value: 'daily'
  }
]

const holdTimeOptions = [
  {
    label: '永远',
    value: 'forever'
  },
  {
    label: '7天',
    value: '7'
  },
  {
    label: '21天',
    value: '21'
  },
  {
    label: '30天',
    value: '30'
  },
  {
    label: '100天',
    value: '100'
  },
  {
    label: '365天',
    value: '365'
  }
]

const habitData = reactive({
  name: '',
  icon: iconMap['yuexiao'].icons[0],
  frequency: {
    type: 'daily'
  },
  holdTime: 'forever'
})

const editHabitData = reactive({
  id: '',
  name: '',
  icon: '',
  frequency: {
    type: 'daily'
  },
  holdTime: 'forever',
  startData: dayjs()
})

const resetData = () => {
  editHabitData.id = ''
  editHabitData.name = ''
  editHabitData.icon = ''
  editHabitData.frequency.type = 'daily'
  editHabitData.holdTime = 'forever'
  editHabitData.startData = dayjs()
  habitData.name = ''
  habitData.icon = iconMap['yuexiao'].icons[0]
  habitData.frequency.type = 'daily'
  habitData.holdTime = 'forever'
  startDate.value = dayjs()
}

const getHabitStreakCount = (habit: HabitItem) => {
  let count = 0
  const currentData = dayjs()
  while (true) {
    if (
      habit.checkInRecords.includes(currentData.subtract(count + 1, 'day').format('YYYY-MM-DD'))
    ) {
      count++
    } else {
      break
    }
  }
  if (habit.checkInRecords.includes(currentData.format('YYYY-MM-DD'))) {
    count++
  }
  return count
}

const handleRightMenuAction = (action: string, data?: HabitItem) => {
  if (!data) return
  resetData()
  editHabitData.name = data.name
  editHabitData.icon = data.icon
  editHabitData.frequency.type = data.frequency.type
  editHabitData.holdTime = 'forever'
  editHabitData.startData = dayjs(data.startDate)
  editHabitData.id = data.id
  switch (action) {
    case 'edit':
      editModalVisible.value = true
      break
    case 'delete':
      modalVisible.value = true
      break
    default:
      break
  }
}

const handleHabitItemClick = (habit: HabitItem) => {
  store.currentHabit = habit
}

const handleEditHabit = () => {
  if (editHabitData.id) {
    const habit = store.habitList.find((item) => item.id === editHabitData.id)
    if (habit) {
      const rawHabit = toRaw(habit)
      window.api.updateHabitData({
        ...rawHabit,
        name: editHabitData.name,
        icon: editHabitData.icon,
        frequency: {
          type: editHabitData.frequency.type
        },
        startDate: editHabitData.startData.format('YYYY-MM-DD')
      })
      store.getHabitList()
      editModalVisible.value = false
    }
  }
}

const handleShowRightMenu = (e: MouseEvent, habit: HabitItem) => {
  e.preventDefault()
  e.stopPropagation()
  if (habitRightMenuRef.value) {
    habitRightMenuRef.value.showMenu(e, habit)
  }
}

const handleShowHabitModal = () => {
  resetData()
  habitModalVisible.value = true
}

const handleCancel = () => {
  modalVisible.value = false
}

const handleEditModalCancel = () => {
  editModalVisible.value = false
}

const handleCancelAddHabit = () => {
  habitModalVisible.value = false
}

const handleAddHabit = () => {
  if (habitData.name.trim().length === 0) {
    return
  }
  const rawData = toRaw(habitData)
  console.log(rawData)
  window.api.addHabitData({
    ...rawData,
    id: Date.now().toString(),
    checkInRecords: [],
    streakDays: 0,
    totalCompletedDays: 0,
    createDate: dayjs().format('YYYY-MM-DD HH:mm:ss').toString(),
    startDate: startDate.value.format('YYYY-MM-DD').toString(),
    endDate: ''
  })
  store.getHabitList()
  habitModalVisible.value = false
}

const handleComfirm = () => {
  modalVisible.value = false
  if (editHabitData.id) {
    window.api.deleteHabitData(editHabitData.id)
    store.getHabitList()
  }
}
</script>

<style scoped lang="scss">
.habit-view {
  height: 100%;
  width: 750px;
  padding: 10px 15px;
  display: flex;
  flex-direction: column;
  border-right: 1px solid var(--xz-card-border);
  background-color: var(--xz-bg);

  .header {
    display: flex;
    height: 40px;
    align-items: center;
    justify-content: space-between;

    .title {
      font-weight: bold;
      font-size: 1.2rem;
    }
  }

  .action {
    display: flex;
    align-items: center;
    gap: 10px;

    .btn {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 25px;
      width: 25px;
      border-radius: 4px;
      cursor: pointer;

      i {
        color: var(--xz-fontcolor);
        font-size: 1rem;
      }
    }
  }

  .habit-list {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .habit-item {
      display: flex;
      align-items: center;
      width: calc(50% - 5px);
      height: fit-content;
      padding: 15px;
      border-radius: 8px;
      background-color: var(--xz-card-bg);
      border: 1px solid transparent;
      transition: all 0.3s ease-out;

      &.active {
        border: 1px solid var(--xz-theme);
      }

      .habit-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background-color: #ffe082;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 15px;

        i {
          font-size: 1.5rem;
          color: #ffa000;
        }

        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
          object-fit: cover;
        }
      }

      .habit-info {
        flex: 1;

        .habit-name {
          font-size: 1rem;
          font-weight: bold;
          margin-bottom: 5px;
        }

        .habit-stats {
          display: flex;
          gap: 15px;
          font-size: 0.8rem;
          color: var(--xz-fontcolor-light);

          span {
            display: flex;
            align-items: center;

            i {
              margin-right: 3px;
            }

            &.total-check {
              i.active {
                color: var(--xz-theme);
              }
            }

            &.streak-check {
              i.active {
                color: var(--xz-pink);
              }
            }
          }
        }
      }

      .habit-action {
        width: 30px;
      }
    }
  }

  .habit-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px;

    img {
      width: 150px;
      height: 150px;
      margin-bottom: 10px;
    }

    .title {
      font-weight: bold;
      font-size: 1.2rem;
      margin-bottom: 5px;
    }

    .text {
      font-size: 0.9rem;
      color: #adb5bd;
    }
  }
}

.add-habit {
  background-color: var(--xz-card-bg);
  width: 100%;
  height: 100%;
  padding: 20px;

  .title {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: bold;
  }

  .form {
    display: flex;
    flex-direction: column;
    width: 100%;
    gap: 10px;

    .row {
      width: 100%;
      justify-content: space-between;
      display: flex;
      align-items: center;

      span {
        font-size: 12px;
        font-weight: bold;
      }

      input {
        width: 350px;
        border: none;
        border-radius: var(--xz-main-radius);
        background: var(--xz-secondbg);
        color: var(--xz-fontcolor);
        min-height: 35px;
        max-height: 35px;
        outline: none;
        font-size: 0.9rem;
        padding: 10px;
        border: 1px solid transparent;

        &:focus {
          border: 1px solid var(--xz-main);
        }

        &::placeholder {
          color: #bfbfbf;
          font-size: 0.9rem;
        }
      }
    }
  }

  .action {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    gap: 10px;

    .btn {
      padding: 5px 30px;
      display: flex;
      align-items: center;
      border-radius: 4px;
      cursor: pointer;

      .text {
        font-weight: 500;
        font-size: 0.8rem;
      }

      &.cancel {
        border: 1px solid var(--xz-theme);
        background-color: var(--xz-secondbg);
      }

      &.save {
        background: var(--xz-blue);
        color: var(--xz-white);
      }
    }
  }
}
</style>
